<?php

namespace App\V3\V3_2\Controllers;

use App\V3\V3_2\Models\AdminModel;
use App\V3\V3_2\Models\OperationLogModel;
use App\V3\V3_2\Models\SystemConfigModel;
use Illuminate\Routing\Controller;
use App\Helper\DBRSAUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class BaseController extends Controller
{
    private $userId = 0;//子账号
    private $mainUserId = 0;//主账号
    private $userType = 0;//用户类型;0:主账号;1:子账号;
    private $outStorageWay = 0;//是否使用批次号;0:否;1:是;
    private $batchTitle;
    private $isVip;//是否开通vip;0:否;1:是;
    private $isSetAsSupplier;//是否将客户作为供应商使用
    private $isShareCustomer;//是否共享客户;0:否;1:是;
    private $isShareExpress;//是否共享快递信息;0:否;1:是;
    private $isUseShelf;//货架库位使用开关1 使用 0关闭
    private $isShareBreakage;//共享报损：1是 0否
    private $isShareOverflow;//共享报溢：1是 0否
    private $isShareStorage;//共享仓库：1是 0否
    private $isShareLog;//共享操作记录：1是 0否
    private $isShareReturn;//共享退货:1:是;0:否;
    private $isShareSell;//共享销售1:是;0:否;
    private $isSharePurchase;//共享采购：1是 0否
    private $expressCheckTimes;//快递查询次数
    private $isShareExpressCalc;//	共享快递价格计算：1是 0否
    private $isShareSupplier;//是否共享供应商;0:否;1:是;
    private $subAccountNumber;//可开启子账号数

    /**
     * token验证
     * BaseController constructor.
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\excepti on\ModelNotFoundException
     */
    public function __construct(Request $request){
        // token获取
        $token = $request->header('token');
        //$token='4637 rKqkyHorQCdikUl0e3F/Pjbq9VUO0RSxdXIPTtDSTp6J0GVOOuls3ECJU1t7QtjgNx9yMN36Dmfx0/O4aQ5/emdUNTJ4SycKHDhpSNBbC708K2oJW7At/sTQk1k9oI6uufTCSaHIKh8AV5tbPisBnhfd4cjboKvq9JMJRc0HPZc=';
        if(empty($token)){
            echo json_encode([
                'code' => 2,
                'msg' => 'token获取失败1',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }
        $array = explode(' ',$token);

        //私钥获取
        $private = SystemConfigModel::getConfigValue('private');
        if(count($array)<2){
            echo json_encode([
                'code' => 2,
                'msg' => 'token参数无效',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }

        //解密加密参数并验证
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        $rsadata = json_decode($rsadata,true);

        if(Redis::GET('user_id_'.$rsadata['userId'].'_reset') == 1) {
            echo json_encode([
                'code' => 4,
                'msg' => '权限信息变更，请重新登录后方可使用',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }

        if(Redis::GET('user_id_'.$rsadata['userId'].'_disabled') == 1) {
            echo json_encode([
                'code' => 5,
                'msg' => '当前账号已被禁用，请及时联系主账号',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }

        if($rsadata['userId'] != $array['0']){
            echo json_encode([
                'code' => 2,
                'msg' => 'token验证失败',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }else{
//            登录有效期检测(未上线先关闭)
//            $userId = Redis::get('user_id_'.$array[0].'_'.$rsadata['type']);
//            if(empty($userId)){
//                echo json_encode([
//                    'code' => 2,
//                    'msg' => 'token已过期',
//                    'data' => '',
//                ],JSON_UNESCAPED_UNICODE);die;
//            }

            //上线后需注释
//            if(!in_array($rsadata['mainUserId'], [1,1086])) {
//                echo json_encode([
//                    'code' => 1,
//                    'msg' => '系统维护中，预计所需时间一个小时。。。。。。',
//                    'data' => '',
//                ],JSON_UNESCAPED_UNICODE);die;
//            }

            $userInfo = AdminModel::select(
                'admin.*',
                'is_vip',
                'is_set_as_supplier',
                'is_share_customer',
                'is_share_express',
                'is_use_shelf',
                'is_share_breakage',
                'is_share_overflow',
                'is_share_store',
                'is_share_operating_record',
                'is_share_sales_return',
                'is_share_sell',
                'is_share_purchase',
                'is_share_billhead',
                'express_check_times',
                'is_share_supplier',
                'is_share_express_price_calculation',
                'sub_account_number'
            )
                ->where([
                    'admin.id' => $rsadata['mainUserId'],
                    'parent_id' => 0,
                    'delete_flag' => 0
                ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();

            $mainInfo = AdminModel::where('id', $rsadata['mainUserId'])->first();
            if($mainInfo['is_sync'] == 0) {
                echo json_encode([
                    'code' => 2,
                    'msg' => 'token已过期，请重新登录1',
                    'data' => '',
                ],JSON_UNESCAPED_UNICODE);die;
            }

            $this->userId = $rsadata['userId'];
            $this->mainUserId = $rsadata['mainUserId'];
            $this->userType = $rsadata['userType'];
            $this->outStorageWay = $userInfo['out_storage_way'];
            $this->batchTitle = $userInfo['batch_title'];
            $this->isVip = $userInfo['is_vip'];
            $this->isSetAsSupplier = $userInfo['is_set_as_supplier'];
            $this->isShareCustomer = $userInfo['is_share_customer'];
            $this->isShareExpress = $userInfo['is_share_express'];
            $this->isUseShelf = $userInfo['is_use_shelf'];
            $this->isUseSerial = $userInfo['is_use_serial'];
            $this->isShareBreakage =$userInfo['is_share_breakage'];
            $this->isShareOverflow = $userInfo['is_share_overflow'];
            $this->isShareStorage = $userInfo['is_share_store'];
            $this->isShareLog = $userInfo['is_share_operating_record'];
            $this->isShareReturn = $userInfo['is_share_sales_return'];
            $this->isShareSell = $userInfo['is_share_sell'];
            $this->isSharePurchase = $userInfo['is_share_purchase'];
            $this->isShareBillhead = $userInfo['is_share_billhead'];
            $this->expressCheckTimes = $userInfo['express_check_times'];
            $this->isShareExpressCalc = $userInfo['is_share_express_price_calculation'];
            $this->isShareSupplier = $userInfo['is_share_supplier'];
            $this->subAccountNumber = $userInfo['sub_account_number'];
        }
    }

    protected function subAccountNumber()
    {
        return $this->subAccountNumber;
    }

    protected function isShareSupplier()
    {
        return $this->isShareSupplier;
    }

    protected function isShareExpressCalc()
    {
        return $this->isShareExpressCalc;
    }

    protected function expressCheckTimes()
    {
        return $this->expressCheckTimes;
    }

    protected function isShareBillhead()
    {
        return $this->isShareBillhead;
    }

    protected function isSharePurchase()
    {
        return $this->isSharePurchase;
    }

    protected function isShareSell()
    {
        return $this->isShareSell;
    }

    protected function isShareReturn()
    {
        return $this->isShareReturn;
    }

    protected function isShareLog()
    {
        return $this->isShareLog;
    }

    protected function isShareStorage()
    {
        return $this->isShareStorage;
    }

    protected function isUseSerial(){
        return $this->isUseSerial;
    }
    /**
     * 获取当前登录用户id
     * change 在 2021/9/24 14:38 创建
     * @return int|string
     */
    protected function getUserId(){
        return $this->userId;
    }

    /**
     *  主账号
     * change 在 2021/10/11 14:47 创建
     * @return int
     */
    protected function getMainUserId(){
        return $this->mainUserId;
    }
    /**
     *  账号类型
     * change 在 2021/10/11 14:47 创建
     * @return int
     */
    protected function getUserTpye(){
        return $this->userType;
    }

    /**
     * 是否共享快递信息;0:否;1:是;
     * 2022/8/22 18:22
     * Author: Sun Wu
     * @return mixed
     */
    protected function isShareExpress()
    {
        return $this->isShareExpress;
    }

    /**
     * 是否使用批次号;0:否;1:是;
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/18 14:05
     * @return int|mixed
     */
    protected function getOutWay() {
        return $this->outStorageWay;
    }

    protected function batchTitle() {
        return $this->batchTitle;
    }

    protected function isVip() {
        return $this->isVip;
    }

    protected function isSetAsSupplier() {
        return $this->isSetAsSupplier;
    }
    protected function isShareCustomer() {
        return $this->isShareCustomer;
    }

    //货架库位使用开关1 使用 0关闭
    protected function isUseShelf()
    {
        return $this->isUseShelf;
    }

    //共享报损：1是 0否
    protected function isShareBreakage()
    {
        return $this->isShareBreakage;
    }
    //共享报溢：1是 0否
    protected function isShareOverflow()
    {
        return $this->isShareOverflow;
    }
    //共享报溢：1是 0否

    /**
     * 成功响应
     * change 在 2021/9/24 14:38 创建
     * @param string $data  响应数据
     * @param string $msg   响应提示
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data='',$msg='success',$code=0){
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }
    /**
     * 失败响应
     * change 在 2021/9/24 14:38 创建
     * @param string $data  响应数据
     * @param string $msg   响应提示
     * @return \Illuminate\Http\JsonResponse
     */
    public function fail($data='',$msg='fail',$code=1){
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }

    /**
     * 操作日志
     * change 在 2021/10/15 13:32 创建
     * @param $remark 操作描述
     * @param $data   操作详细内容
     */
    public function log($remark,$data){
        $res = OperationLogModel::insert([
            'main_id'=>$this->getMainUserId(),
            'user_id'=>$this->getUserId(),
            'remark'=>$remark,
            'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
            'ip'=>$_SERVER["REMOTE_ADDR"],
            'created_at'=>time(),
        ]);
        if(!$res){
            $this->fail('操作日志插入失败');
        }
    }

    public function operateLog($remark, $data, $time)
    {
        $res = OperationLogModel::insert([
            'main_id'=>$this->getMainUserId(),
            'user_id'=>$this->getUserId(),
            'remark'=>$remark,
            'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
            'ip'=>$_SERVER["REMOTE_ADDR"],
            'created_at'=>$time,
        ]);
        if(!$res){
            $this->fail('操作日志插入失败');
        }
    }
}
